import { onBeforeUnmount, ref } from 'vue';

function useThrottle(callback: Function, delay: number = 100) {
  let timerId = ref<ReturnType<typeof setTimeout> | null>(null); // Updated type
  const cancel = () => {
    if (timerId.value !== null) {
      clearTimeout(timerId.value);
      timerId.value = null;
    }
  };

  const throttledCallback = (...args: any[]) => {
    if (!timerId.value) {
      timerId.value = setTimeout(() => {
        callback(...args);
        timerId.value = null;
      }, delay);
    }
  };

  onBeforeUnmount(cancel); // 在组件卸载前清除定时器

  return [throttledCallback, cancel];
}

export default useThrottle;
